//
//  KKTabBar.m
//  DoMi
//
//  Created by 康凯 on 16/10/27.
//  Copyright © 2016年 kk. All rights reserved.
//

#import "KKTabBar.h"

@interface KKTabBar()

//图片
@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) UIButton * selectItem;

@end

@implementation KKTabBar

-(NSArray *)datas{
    if(!_datas){
        _datas = @[@"learn",@"commun",@"my"];
    }
    return _datas;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        for(int i=0;i<self.datas.count;i++){
//            UIButton *item = [UIButton buttonWithType:UIButtonTypeCustom];
            UIButton *item=[[UIButton alloc]initWithFrame:CGRectMake(screenWidth/3*i, 0, screenWidth/3, 48)];
            
            item.adjustsImageWhenHighlighted = NO;
            [item.imageView setContentMode:UIViewContentModeScaleAspectFill];
            [item setImage:[UIImage imageNamed:self.datas[i]] forState:UIControlStateNormal];
            [item setImage:[UIImage imageNamed:[self.datas[i] stringByAppendingString:@"_select"]] forState:UIControlStateSelected];
            item.tag=i;
            
            if (i == 0) {
                item.selected = YES;
                self.selectItem = item;
            }
            
            [item addTarget:self action:@selector(clickItem:) forControlEvents:UIControlEventTouchUpInside];
            
            [self addSubview:item];
        }
        
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    CGFloat width = self.frame.size.width / self.datas.count;
    for (UIView * btn in self.subviews) {
        long i=btn.tag;
        btn.frame = CGRectMake(i * width, 0, width, self.frame.size.height);
    }

}

-(void)clickItem:(UIButton *)btn{
    if ([self.delegate respondsToSelector:@selector(tabbar:clickIndex:)]) {
        [self.delegate tabbar:self clickIndex:btn.tag];
    }
    //将上一个按钮的选中状态置为NO
    self.selectItem.selected = NO;
    
    //将正在点击的按钮状态置为YES
    btn.selected = YES;
    
    //将当前按钮设置成上一个按钮
    self.selectItem = btn;
}

@end
